package online.hxstar.learn.chapter2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author xinghu
 * @version 1.0
 * @date 2019/11/7 5:12 下午
 */
@ChannelHandler.Sharable
@Slf4j
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//当被通知 Channel 是活跃的时候，发 送一条消息
		ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!",
				CharsetUtil.UTF_8));
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		// 记录已接收 消息的转储
		log.info("Client received: {}", msg.toString(CharsetUtil.UTF_8));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		//在发生异常时， 记录错误并关闭 Channel
		cause.printStackTrace();
		ctx.close();
	}
}
